#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define MAX_NUM_THREADS 100

int n;

void *miThread(void *threadid) {
   long tid;

   tid = (long)threadid;
   printf("Hola, soy el thread %ld\n", tid);
   printf("Soy el #%d en pasar...\n", n++);
   pthread_exit(NULL);
}

int main(int argc, char *argv[]) {
   pthread_t threads[MAX_NUM_THREADS];
   int numThreads, rc;
   void *status;
   long t;

   if (argc != 2) {
      printf("Uso correcto: %s <numero-de-threads>\n", argv[0]);
      exit(EXIT_FAILURE);
   }

   numThreads = atoi(argv[1]);
   if (numThreads <= 0) {
      printf("<numero-de-threads> debe ser >= 0\n");
      exit(EXIT_FAILURE);
   }

   n=1;

   // Se crean numThread threads
   for(t=0;t<numThreads;t++) {
      rc = pthread_create(&threads[t], NULL, miThread, (void *)t);
      if (rc) {
         printf("Error creando thread %ld: %d\n", t, rc);
         exit(EXIT_FAILURE);
      }
   }

   // Join: Espera a que todos terminen
   for(t=0;t<numThreads;t++) {
      rc = pthread_join(threads[t], &status);
      if (rc) {
         printf("Error haciendo join con thread %ld: %d\n", t, rc);
         exit(EXIT_FAILURE);
      }
   }
   printf("Todos los threads terminaron!\n");

   pthread_exit(NULL);
}

